#include <func.h>
#define N 200000
typedef struct 
{
    pthread_mutex_t mutex;
    int num;
}data_t;

int main(int argc,char **argv)
{

    int shmid = shmget(IPC_PRIVATE,sizeof(data_t),IPC_CREAT|0600);
    ERROR_CHECK(shmid,-1,"shmget");

    data_t *pdata = (data_t*)shmat(shmid,NULL,0);
    ERROR_CHECK(pdata,NULL,"shmat");

    int ret;

    ret = pthread_mutex_init(&(pdata->mutex),NULL);
    pdata->num = 0;

    struct timeval start,end;
    gettimeofday(&start,NULL);
    if(!fork())
    {
    //son
        for(int i = 0;i<N;++i)
        {
            pthread_mutex_lock(&pdata->mutex);
            printf("child:adding,now :%d\n",pdata->num);
            pdata->num+=1;
            pthread_mutex_unlock(&pdata->mutex);
        }
        
    }else{
    //parent
        
        for(int i = 0;i<N;++i)
        {
            pthread_mutex_lock(&pdata->mutex);
            printf("parent:adding ,now :%d\n",pdata->num);
            pdata->num+=1;
            pthread_mutex_unlock(&pdata->mutex);
        }
        wait(NULL);
        gettimeofday(&end,NULL);
        printf("reslut:%d\n",pdata->num);
        printf("time: %ld\n",(end.tv_sec - start.tv_sec)*1000000+end.tv_usec - start.tv_usec);
        shmctl(shmid,IPC_RMID,NULL);
    }

    return 0;
}

